import logging

import pytest

from resource.pom.hap import Hap
from resource.pom.settings import Settings
from utils.manager import Images


@pytest.fixture(autouse=True)
def uninstall_hap(device):
    logging.info('预置条件：镜像版本正确、联网正常，浏览器hap安装正常')
    device.install_hap(Hap.package_path)
    connect_status = Settings.connect_wifi(device)
    assert connect_status, 'wifi连接失败'
    yield
    try:
        device.uninstall_hap(Hap.bundle_name)
    except:
        pass


class Test:
    app = Hap

    # 1.打开浏览器
    # 2.浏览器中首页选择百度
    # 3.点击百度搜索框，有结果1
    # 4.百度搜索框中输入任意字符，点击搜索，有结果2
    # 1.软键盘弹出
    # 2.软键盘收起，搜索结果中有相关搜索内容

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.打开浏览器，加载微博')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        device.wait(5)
        device.refresh_layout()
        # device.double_click_element(device.get_element_by_text('weibo'))
        device.click_element(device.get_element_by_text('weibo'))
        device.wait(10)
        logging.info('步骤2.单击打开某条微博的图片，点击左下角的返回按钮，有结果1')
        device.refresh_layout()
        weibo_page = device.save_snapshot_to_local('wb_home.jpeg')
        Images.crop_picture(weibo_page)
        articles = device.get_elements_by_type('article')
        win_name, win_id = device.get_focus_window()
        images = device.get_elements_by_condition(condition={'hostWindowId': win_id, 'type': 'image'})
        for atc in articles:
            find = False
            x1, y1, x2, y2 = device.get_element_area(atc)
            for img in images:
                x, y = device.center_of_element(img)
                # 说明这个图片在这条微博中
                if x1 < x < x2 and y1 < y < y2:
                    device.click(x, y)
                    find = True
                    break
            if find:
                break
        device.wait(10)
        single_pic = device.save_snapshot_to_local('wb_pic.jpeg')
        Images.crop_picture(single_pic)
        logging.info('预期结果1.图片查看大图加载成功，返回成功')
        similarity = Images.compare_image_similarity(weibo_page, single_pic)
        assert similarity < 1, '图片点开失败'
        device.click(*self.app.back_btn)
        back_pic = device.save_snapshot_to_local('wb_home1.jpeg')
        Images.crop_picture(back_pic)
        s1 = Images.compare_image_similarity(back_pic, weibo_page)
        s2 = Images.compare_image_similarity(back_pic, single_pic)
        assert s1 > s2, '返回失败'
